package controllers

import (
	comm "com.wangzhumo.lottery/common"
	"com.wangzhumo.lottery/models"
	"com.wangzhumo.lottery/services"
	"fmt"
	"github.com/kataras/iris/v12"
)

type IndexController struct {
	Ctx            iris.Context
	ServiceUser    services.UserService
	ServiceIp      services.BlackIpService
	GiftServices   services.GiftServices
	CodeService    services.CodeService
	UserDayService services.UserDayService
	ResultService  services.ResultService
}

// Get 首页
func (c *IndexController) Get() string {
	c.Ctx.Header("Content-Type", "text/html")
	return "welcome to Go抽奖系统，<a href='/public/index.html'>开始抽奖</a>"
}

// GetGifts 获取礼物列表
func (c *IndexController) GetGifts() map[string]interface{} {
	response := make(map[string]interface{})
	response["code"] = 0
	response["msg"] = ""
	// find gift list
	gifts, err := c.GiftServices.GetAll(true)
	giftList := make([]models.LtGift, 0)
	if err == nil {
		for _, gift := range gifts {
			// 写入返回值
			if gift.SysStatus == 0 {
				giftList = append(giftList, gift)
			}
		}
	}
	response["gifts"] = giftList
	response["msg"] = "ok"
	return response
}

// GetNewprize 获取最近中奖
func (c *IndexController) GetNewprize() map[string]interface{} {
	response := make(map[string]interface{})
	response["code"] = 0
	response["msg"] = ""
	// find gift list
	gifts, err := c.GiftServices.GetAll(true)
	giftList := make([]models.LtGift, 0)
	if err == nil {
		for _, gift := range gifts {
			// 写入返回值
			if gift.SysStatus == 0 {
				giftList = append(giftList, gift)
			}
		}
	}
	response["gifts"] = giftList
	return response
}

// GetLogin 登录
func (c *IndexController) GetLogin() {
	uid := comm.Random(100000)
	loginUser := &models.ObjLoginUser{
		UID:      uid,
		Username: fmt.Sprintf("admin-%d", uid),
		Now:      comm.NowUnix(),
		Ip:       comm.ClientIp(c.Ctx.Request()),
	}
	refer := c.Ctx.GetHeader("Referer")
	if refer == "" {
		refer = "/public/index.html?from=login"
	}
	// 设置到返回
	comm.SetLoginUser(c.Ctx.ResponseWriter(), loginUser)
	// 跳转
	comm.Redirect(c.Ctx.ResponseWriter(), "/public/index.html?from=login")
}

// GetLogout 退出登录
func (c *IndexController) GetLogout() {
	// 设置到返回
	comm.SetLoginUser(c.Ctx.ResponseWriter(), nil)
	// 跳转
	comm.Redirect(c.Ctx.ResponseWriter(), "/public/index.html?from=logout")
}
